package faceb.server.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import faceb.server.dao.ResourceDao;
import faceb.server.logger.MyLogger;
import faceb.server.model.AjaxResponse;
import faceb.server.model.Resource;
import faceb.server.model.User;
import faceb.server.util.CharSetUtil;
import faceb.server.util.ServerFinal;
import faceb.server.util.UUIDUtil;
import faceb.server.util.UploadUtils;

@Controller
public class ResourceController {

	@javax.annotation.Resource(name = "resourceDao")
	private ResourceDao resourceDao;

	private Gson gson = new Gson();

	@RequestMapping(value = "/resources/upload")
	public String upload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return "upload";
	}

	@RequestMapping("/resources/download/{resourceid}")
	public void download(@PathVariable("resourceid") String resourceid,
			HttpServletResponse resp) throws Exception {
		resp.setCharacterEncoding(ServerFinal.CHAR_ENCODING);
		if (StringUtils.isEmpty(resourceid)) {
			return;
		}
		Resource r = resourceDao.getResourceById(resourceid);
		if (r == null) {
			PrintWriter out = resp.getWriter();
			out.print("资源不存在");
			return;
		}
		File file = Paths.get(ServerFinal.RESOURCE_DIR, r.getR_u_id(),
				"resources", r.getR_name()).toFile();
		if (!file.exists()) {
			PrintWriter out = resp.getWriter();
			out.print("资源不存在");
			return;
		}

		OutputStream os = resp.getOutputStream();
		String filename = URLEncoder.encode(r.getR_name(),
				ServerFinal.CHAR_ENCODING);
		resp.addHeader("Content-Disposition", "attachment;filename=" + filename
				+ "");
		FileInputStream fis = new FileInputStream(file);
		byte[] b = new byte[fis.available()];
		fis.read(b);
		os.write(b);
		fis.close();
		os.close();
	}

	@RequestMapping(value = "/resources/dealupload", method = RequestMethod.POST)
	public void handleupload(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> paramsAndFiles = UploadUtils
				.getUploadFilesAndParams(request);
		Map<String, String> params = (Map<String, String>) paramsAndFiles
				.get("params");
		List<File> files = (List<File>) paramsAndFiles.get("files");

		String userid = params.get("userid");
		String filename = files.get(0).getName();
		String filepath = files.get(0).getAbsolutePath();
		String resourceDir = ServerFinal.RESOURCE_DIR;
		User u = (User) request.getSession().getAttribute("user");

		if (!Objects.equals(userid, u.getU_id())
				|| StringUtils.isEmpty(filepath)
				|| StringUtils.isEmpty(filename)) {
			return;
		}
		String r_id = UUIDUtil.getCode(20);
		long now = System.currentTimeMillis();
		Resource r = new Resource(r_id, userid, filename, now);

		FileUtils.moveFileToDirectory(new File(filepath),
				Paths.get(resourceDir, userid + "/" + "resources").toFile(),
				true);
		int result = resourceDao.insertResource(r);
		/*
		 * if (result == 1) request.setAttribute("message", "文件上传处理成功"); else
		 * request.setAttribute("message", "文件上传处理失败");
		 * request.getRequestDispatcher("/WEB-INF/pages/message.jsp").forward(
		 * request, response);
		 */
		response.sendRedirect("/faceb-cupt/tpl/center/users/" + userid);
	}

	/**
	 * 上传临时文件
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/resources/dealupload/tmp", method = RequestMethod.POST)
	@ResponseBody
	public String handleuploadTmp(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> paramsAndFiles = UploadUtils
				.getUploadFilesAndParams(request);
		List<File> files = (List<File>) paramsAndFiles.get("files");
		Map<String, String> params = (Map<String, String>) paramsAndFiles
				.get("params");
		String type = params.get("type");
		String userid = ((User) request.getSession().getAttribute("user"))
				.getU_id();
		String filename = files.get(0).getName();
		String filepath = files.get(0).getAbsolutePath();
		String resourceDir = ServerFinal.RESOURCE_DIR;
		User u = (User) request.getSession().getAttribute("user");

		if (!Objects.equals(userid, u.getU_id())
				|| StringUtils.isEmpty(filepath)
				|| StringUtils.isEmpty(filename)) {
			return null;
		}
		long now = System.currentTimeMillis();

		File tmpFile = new File(filepath);
		String tmpFileName = tmpFile.getName();
		String suffix = tmpFileName.substring(tmpFileName.lastIndexOf("."));
		File tmpDir = Paths.get(resourceDir, userid, "pics", "tmp").toFile();
		tmpDir.mkdirs();
		File newFile = Paths.get(resourceDir, userid, "pics", "tmp",
				String.valueOf(now) + suffix).toFile();
		FileUtils.moveFile(tmpFile, newFile);
		request.getSession().setAttribute(String.valueOf(now),
				newFile.getAbsolutePath()); // 在session中设置临时图片路径
		List<String> filePaths = (List<String>) request.getSession()
				.getAttribute(userid + "upload");
		if (filePaths == null) {
			filePaths = new ArrayList<String>();
		}
		filePaths.add(newFile.getAbsolutePath());
		request.getSession().setAttribute(userid + "upload", filePaths);

		String fileurl = ServerFinal.SERVER_URL
				+ "resources/dealdownload/tmp?ts=" + now;
		String jsonStr = "<script>	top." + type
				+ "({	status: 0,	info: '',	data: '" + fileurl + "'	})</script>";

		return jsonStr;

	}

	@RequestMapping(value = "/resources/dealdownload/tmp", method = RequestMethod.GET)
	public void handledownloadTmp(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String ts = request.getParameter("ts");
		String filePath = (String) request.getSession().getAttribute(ts);
		FileInputStream fis = new FileInputStream(filePath);
		byte[] b = new byte[fis.available()];
		fis.read(b);
		fis.close();
		OutputStream os = response.getOutputStream();
		os.write(b);
		os.close();
	}

	@RequestMapping("/resources/users/{userid}")
	@ResponseBody
	public String getResourcesByUserid(@PathVariable("userid") String userid,
			HttpServletResponse resp) {

		AjaxResponse ar = new AjaxResponse();
		List<Resource> resources = resourceDao.getResourcesByUserid(userid);
		ar.setStatus("0");
		ar.setInfo("success");
		ar.setData(resources);
		return CharSetUtil.getRespBodyStr(gson.toJson(ar));
	}

	@RequestMapping(value = "/userlogo/users/{userid}", method = RequestMethod.GET)
	public void getUserLogo(@PathVariable("userid") String userid,
			HttpServletResponse response) throws Exception {

		File userLogoFile = Paths.get(ServerFinal.RESOURCE_DIR, userid,
				"logo.jpg").toFile();
		if (!userLogoFile.exists()) {
			userLogoFile = Paths.get(ServerFinal.RESOURCE_DIR,
					"default_logo.jpg").toFile();
		}
		FileInputStream fis = new FileInputStream(userLogoFile);
		byte[] b = new byte[fis.available()];
		fis.read(b);
		fis.close();
		OutputStream os = response.getOutputStream();
		os.write(b);
		os.close();
	}

	@RequestMapping(value = "/userlogo/upload", method = RequestMethod.POST)
	public void uploadUserLogo(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {
		Map<String, Object> paramsAndFiles = UploadUtils
				.getUploadFilesAndParams(req);
		List<File> files = (List<File>) paramsAndFiles.get("files");
		String uid = ((User)req.getSession().getAttribute("user")).getU_id();
		if (files.size() < 1) {
			return;
		}
		File file = files.get(0);
		File oldFile = Paths.get(ServerFinal.RESOURCE_DIR+uid,"logo.jpg").toFile();
		if(oldFile.exists())
			oldFile.delete();
		
		FileUtils.moveFile(file, Paths.get(ServerFinal.RESOURCE_DIR+uid,"logo.jpg").toFile());
		resp.sendRedirect("/faceb-cupt/tpl/profile");
		
		
	}

}
